/**
 * http 请求模块
 *
 * 用法：
 *  1.接口请求
 *    http[api].then(res => {}).catch(err => {})
 *
 *  2.http请求方法设置
 *    a.设置请求头
 *      http.$setHeader(key, val)
 *      http.$setHeader({ key1: val1, key2: val2 })
 */

import config from '../../config/index'
import apiMap from './apiMap'
import { ResponseException, NetworkException } from './Exception'
import { ensureTailHasSlash, ensureCapitalHasNotSlash } from '../../utils/index';
let util = require('../../utils/index');
const { api: { url: apiBaseUrl, statusCode } } = config

const http = {}

const header = {
  'content-type': 'application/x-www-form-urlencoded',
  'token': 'abc12345'//wqeqewqeq
}

Object.keys(apiMap).forEach(requestMethod => {
  const methodApis = apiMap[requestMethod]
  Object.keys(methodApis).forEach(api => {
    http[api] = data => {
      header.token = 'abc12345'
      return new Promise((resolve, reject) => {
        wx.request({
          url: ensureTailHasSlash(apiBaseUrl) + ensureCapitalHasNotSlash(methodApis[api].trim()),
          data,
          header,
          method: requestMethod.toUpperCase(),
          success(res) {
            let app = getApp();
            var isOpenToast = app.globalData.isOpenToast;
            const resData = res.data
            const { status, data, msg } = resData
            if (status === statusCode.success) {
              resolve(data ? data : resData)
            } else {
              if ((status == -100 || status == -200) && !isOpenToast){
                //不是司机
                app.globalData.isOpenToast = true;
                wx.showModal({
                  title: '提示',
                  content: msg,
                  success: function(res) {
                    if (res.confirm) {
                      if (status == -100){
                        //跳转注册
                        util.default.go('/pages/account/register/step1/RegisterStep1');
                      }
                      if (status == -200){
                        //跳转注册成功页面 并弹出审核失败原因
                        util.default.go('/pages/commitSuccess/commitSuccess?getStatus=200&error='+msg);
                      }                      
                    } else if (res.cancel) {

                    };
                    app.globalData.isOpenToast = false;
                  }
                })
              }
              reject(new ResponseException(msg, resData))
            }
          },
          fail(err) {
            reject(new NetworkException('网络错误', err))
          }
        })
      })
    }
  })
})
/*******************
 * 设置请求头
 ******************/
const isString = str => typeof str === 'string'

const _setHeader = (key, val) => {
  if (!isString(key)) throw new TypeError('header key 类型错误，期待类型为 string')
  if (!isString(val)) throw new TypeError('header val 类型错误，期待类型为 string')
  header[key] = val
}

http.$setHeader = (...rest) => {
  if (rest.length === 1) {
    const settingObj = rest[0]
    if (!(settingObj instanceof Object)) throw new TypeError('header setting 类型错误，期待类型为 object')
    Object.keys(settingObj).forEach(key => {
      _setHeader(key, settingObj[key])
    })
  } else if (rest.length >= 2) {
    _setHeader(rest[0], rest[1])
  }
}

export default http
